/***
** 激活程序
** 激活新增组件的事件绑定，事件响应
**/
define(['../model/data','./component', '../plugins/account'],function(DATA,com, account){
    return function(hid,da,node,inx){
            var self = this;
            var args = arguments;
            var pre = "#" + hid + " ";
            var tags = pre + ".js-example-tags";
            var btns = pre + "button.btn-plus:has(i.glyphicon-plus)";
            var close = pre + "div.alert-dismissible";
            var theNode = node || $("#"+hid).find(".user-body>li:first");

            if(hid != "price-config-field")
                theNode.attr("index",inx);

            this.componentInit = function(){
                com(hid,node,da,inx);
            };

            this.copy = function(fa,cloneNode,id){
                cloneNode.attr("index",parseInt(cloneNode.attr("index"))+1);
                var btn = fa.find("button.btn-plus:has(i.glyphicon-plus)");
                if(id=="WirelessConnection"||id == "Gender") {//无线或者 版位
                    var len = fa.children().length;
                    if(id=="WirelessConnection"||id == "Gender")for(var i=0;i<len;i++){
                        $(fa.children()[i]).find("input[type=radio]").attr("name",id+i);
                    }
                    cloneNode.find("input[type=radio]").attr("name",id+len+1);
                    //$(this).addClass("hidden");//不显示
                    if(id=="WirelessConnection"){
                        var val = cloneNode.find("input[type=radio]:checked").val();
                        if(val==0){
                            cloneNode.find("input[type=radio][value='1']").prop("checked",true);
                        }else{
                            setTimeout(function(){
                                cloneNode.find("input[type=radio][value='0']").prop("checked",true);
                            });
                        }
                    }else if(id == "Gender"){
                        var vals = [];
                        $("#Gender").find("input[type=radio]:checked").each(function(index,item){
                            vals.push($(item).val());
                        });
                        if(vals.indexOf("0")==-1){
                            setTimeout(function(){
                                cloneNode.find("input[type=radio][value='0']").prop("checked",true);
                            });
                        }else if(vals.indexOf("1")==-1){
                            setTimeout(function(){
                                cloneNode.find("input[type=radio][value='1']").prop("checked",true);
                            });
                        }else{
                            setTimeout(function(){
                                cloneNode.find("input[type=radio][value='2']").prop("checked",true);
                            });
                        }
                    }
                }else if(id=="PageTypes"){
                    var checked = false;
                    $("#PageTypes").find("input[type=checkbox][value='1']").each(function(index,item){
                        checked = $(this).is(':checked');
                    });
                    if(DATA.sessionData.isSupportInstagram=='N'){
                        cloneNode.find("input[type=checkbox][value='1']").prop("checked", false);
                    }else{
                        cloneNode.find("input[type=checkbox]").prop("checked", false);
                    }
                }else if(id=="CustomAudience"){//自定义受众
                    cloneNode.find("div.hybrbox").empty();
                }else if(id=="sim-audience"){//相似受众
                    cloneNode.find("div.sim-box").empty();
                }
                else if(id=="Age"){ //年龄
                    cloneNode.find("div.age-ranger").empty();
                }else if(id=="price-config-field"){
                    //处理输入框
                    var sPrice = cloneNode.find("input.price-input[placeholder]");
                    sPrice.val("").removeClass("anim_image_glow");
                    sPrice.next("div.tooltip").css("opacity",0);
                    var locIndex=cloneNode.attr("index");
                    //处理radio name 问题
                    var radioName= cloneNode.find("input[type=radio]").attr("name");
                    cloneNode.find('input[type=radio]').attr("name",radioName+"loc"+locIndex);
                    //添加支付方式重新渲染广告账号列表
                    account.initAccount(DATA.cache.entrustAccounts);
                }else if(id == "ad-txt"){
                    cloneNode.find("textarea").val();
                    cloneNode.find("div.text-range-warning").text("");
                }
                if(id == "Interests"){
                    cloneNode.find("div.drop-lang").empty();
                    cloneNode.find("select").empty().siblings("span.select2").remove();
                    cloneNode.find("div.shortcut-drop").addClass("hidden");
                }
                if(id=="Location"){
                    cloneNode.find(".loc-alert").removeAttr("style");
                    cloneNode.find("select.cs-search-ins").empty().siblings("span.select2").remove();
                    cloneNode.find("div.clu-drop").empty();
                    cloneNode.find("div.cou-drop").empty();
                    cloneNode.find("div.peo-group").empty();
                }
                fa.append(cloneNode);
                btn.remove();
                return cloneNode;
            }

            this.buttonInit = function (){
                var btn = node?node.find("button.btn-plus:has(i.glyphicon-plus)"):$(btns);
                var id = hid;
                //添加
                btn.unbind("click").on("click",function(e){
                    e.stopPropagation();
                    var fa = $(this).parent().parent();//ul
                    var cloneNode = $(this).parent().clone();
                    var data=undefined;
                    if(id=="price-config-field"){
                        cloneNode = $(this).parent().clone(true);
                            //第几组的index
                        var gindex = $(this).closest(".one-dist").attr("loc-index");
                        var locIndex= parseInt($(this).parent().attr("index")) + 1;
                        DATA.getBidInfoVo(gindex, locIndex);
                        data = DATA.addItem(id,gindex,locIndex);
                    }else if(id == "WirelessConnection"){
                        var v = parseInt(cloneNode.find("input[type=radio]:checked").val());
                        if(v==0){
                            data = DATA.addItem(id,1);
                        }else{
                            data = DATA.addItem(id,0);
                        }
                    }else if(id=="Gender"){
                        var vs = [];
                        $("#Gender").find("input[type=radio]:checked").each(function(index,item){
                            vs.push($(item).val());
                        });
                        if(vs.indexOf("0")==-1){
                            data = DATA.addItem(id,0);
                        }else if(vs.indexOf("1")==-1){
                            data = DATA.addItem(id,1);
                        }else{
                            data = DATA.addItem(id,2);
                        }
                    }else if(id=="PageTypes"){
                        if(DATA.sessionData.isSupportInstagram=='N'){
                            data = DATA.addItem(id, [0]);
                        }else{
                            //多版位添加不做自动勾选
                        }
                    }else{
                        data = DATA.addItem(id);
                    }

                    self.copy(fa,cloneNode,id);

                    if(id=="WirelessConnection"||id=="PageTypes"||id == "Gender"){
                        var len = fa.children().length;
                        if(id=="Gender" && len>=DATA.Gender.GenderCount ){
                            $(this).addClass("hidden");
                        }else if(id=="PageTypes"){
                            if(DATA.sessionData.isSupportInstagram=='Y'&&len>=5){
                                $(this).addClass("hidden");
                            }else if(DATA.sessionData.isSupportInstagram!='Y'&&len>2){
                                $(this).addClass("hidden");
                            }

                        }else if(id!="PageTypes"&&len>=2){
                            $(this).addClass("hidden");
                        }
                    }

                    args.callee(id,data,cloneNode,parseInt(cloneNode.attr("index")));
                    if(window.existsPreviewUserAudience){//如果存在标记,则说明有生成新的用户定位
                        if(hid != 'ad-txt' && hid != 'price-config-field'){ //用户定位下面不用
                            cloneNode.find('.alert-dismissible').addClass('border-green');
                        }
                    }

                });

                //删除
                $(close).unbind("close.bs.alert").on("close.bs.alert",function(e){
                    var the = $(this).parent();//<li>
                    var delIndex = the.attr("index");
                    $(the).nextAll("li").each(function(ind,ele){
                        $(ele).attr("index",(parseInt($(ele).attr("index"))-1));
                    });
                    var  pa = the.parent();//<ul>
                    var len = pa.children().length -1;
                    if(the.has("button.btn-plus")){
                        var btnclone = the.find("button.btn-plus").clone(true);
                        the.prev().append(btnclone);
                    }
                    if(len <= 2){
                        the.siblings().find("button.close").addClass("hidden");
                    }
                    if(id == "WirelessConnection"||id=="PageTypes"||(id=="Gender"||len==(DATA.Gender.GenderCount -1))){//版位或者无线或者性别
                        the.find("button.btn-plus").removeClass("hidden");
                    }
                    if(id=="price-config-field"){
                        var gIndex = the.closest(".one-dist").attr("loc-index");
                        var locIndex= the.attr("index");
                        DATA.delItem(id,gIndex,locIndex);
                        //删除支付方式重新渲染广告账号列表
                        account.initAccount(DATA.cache.entrustAccounts);
                    } else {
                        DATA.delItem(id,delIndex);
                    }

                    the.remove();
                });
                //点击选择  针对radio
                if(id=="WirelessConnection"||id == "PageTypes"||id=="Gender"){
                    $("#"+id+" label>:input").unbind("change").on("change",function(e){
                        e.stopImmediatePropagation();
                        var the;//li
                        if (id == "Gender"){
                            the = $(this).parent().parent().parent().parent();
                        } else {
                            the = $(this).parent().parent().parent();
                        }
                        var delIndex = the.attr("index");
                        if(id!="PageTypes"){
                            var val = the.find("input:checked").val()
                        }else{
                            //版位选择后，进行数据更新
                            val=[];
                            the.find("input[type=checkbox]").each(function(index,item){
                                if($(this).is(':checked')){
                                    val.push($(this).val());
                                }
                            });
                        }
                        DATA.update(id,delIndex,val);
                    });
                }
            };
            this.componentInit();
            this.buttonInit();

        // $('.input-drop.dropdown').off('click').on('click',function(){
        //             var that= this;
        //             setTimeout(function() {
        //                 $(that).toggleClass('open',!$(this).hasClass('open'))
        //             },200)
        //         })
    };
});
